<?php
/**
 * Created by PhpStorm.
 * Date: 2016/11/16
 * Time: 下午2:05
 */
namespace app\api\controller;

use app\api\model\UserException;
use app\common\model\Contact;
use app\common\model\Server;
use app\common\model\Settings;
use think\Exception;
use think\facade\Db;
use think\facade\Log;

class Chat extends Notify
{
    public function index(){

        //回调get参数
        $SdkAppid = input('get.SdkAppid');
        $Sign = input('get.Sign');
        $RequestTime = input('get.RequestTime');

        //系统设置
        $system = Settings::getSystem();

        //appid校验
        if(empty($SdkAppid) || $SdkAppid!=$system['tx_im_appid']){
            return $this->fail('参数错误');
        }

        //签名校验
        $hash = hash('sha256', $system['tx_im_notify_token'].$RequestTime);
        if($hash != $Sign){
            return $this->fail('签名错误');
        }

        //时间
        $time = time()-$RequestTime;
        if($time>60){
            return $this->fail('无效请求');
        }

		$post = file_get_contents('php://input');
        $log = $post;

        $post = json_decode($post,true);
        if(empty($post)){
            return $this->fail('请求包体有误');
        }

        //回调类型
        $CallbackCommand = $post['CallbackCommand'];

        //记录聊天
        Log::write($log,$CallbackCommand);

        switch ($CallbackCommand){
            case "C2C.CallbackBeforeSendMsg"://单聊发送前
                return $this->beforeMsg($post);
                break;
            case "C2C.CallbackAfterSendMsg"://单聊发送后
                //被联系人是否是服务商更新联系时间
                Server::callChat($post['From_Account'],$post['To_Account']);
                //单聊加好友
                Contact::msgAddContact($post['From_Account'],$post['To_Account']);
            default:
               //不在需要的回调范围内不做处理
        }

        return $this->success();
    }

    private function beforeMsg($post){

//        if($post['From_Account']==$post['To_Account']){
//            return $this->msgRes(1,'请勿同自己聊天');
//        }

        return $this->msgRes(0);
    }

    /**
     * 发消息返回结果
     * @param $code
     * @param string $info
     * @return false|string
     */
    private function msgRes($code,$info=''){
        $res = [
            'ActionStatus'=>'OK',
            'ErrorInfo'=>$info,
            'ErrorCode'=>$code //ErrorCode 0 允许发言 1 禁止发言 2 静默丢弃（自己看到是发了但对方收不到）
        ];

        return json_encode($res,JSON_UNESCAPED_UNICODE);
    }

    /**
     * 通用成功
     * @return false|string
     */
    private function success(){
        return json_encode([
            'ActionStatus'=>'OK',
            'ErrorInfo'=>'',
            'ErrorCode'=>0
        ],JSON_UNESCAPED_UNICODE);
    }

    /**
     * 通用失败
     * @param $info
     * @return false|string
     */
    private function fail($info){
        return json_encode([
            'ActionStatus'=>'FAIL',
            'ErrorInfo'=>$info,
            'ErrorCode'=>1
        ],JSON_UNESCAPED_UNICODE);
    }
}
